package com.rc.common.advice;

import com.rc.common.util.JsonUtil;
import com.rc.common.util.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一响应包装为R
 */
@RestControllerAdvice(basePackages = "com.rc.web.controller")
public class CommonResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 跳过所有返回 ResponseEntity 或 byte[] 的方法
        return !(returnType.getParameterType().equals(ResponseEntity.class) ||
                returnType.getParameterType().equals(byte[].class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof R){
            return body;
        }

        if (body instanceof String){
            return JsonUtil.toJson(R.success(body));
        }

        return R.success(body);
    }
}
